import random
import logging
import json

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class QuizModule:
    def __init__(self):
        # 判断题模板
        self.true_false_templates = [
            "判断以下说法是否正确：{}",
            "请问这句话对不对：{}",
            "以下说法是否正确：{}",
            "关于{}，这种说法对吗？",
            "下列关于{}的说法是否正确？"
        ]
        
        # 选择题模板
        self.choice_templates = [
            "以下哪种物品属于{}？",
            "下列哪个选项属于{}？",
            "在给出的选项中，哪个是{}？",
            "请从以下选项中选出{}：",
            "以下哪一项应该分类为{}？"
        ]
        
    def generate_question_variant(self, question, q_type):
        """生成问题变体"""
        try:
            if q_type == 'true_false':
                # 对判断题，提取关键信息
                content = question.split('：', 1)[1] if '：' in question else question
                # 如果内容中包含"属于"，提取主题
                if '属于' in content:
                    topic = content.split('属于')[0].strip()
                    template = random.choice(self.true_false_templates)
                    return template.format(content)
                return random.choice(self.true_false_templates[:3]).format(content)
                
            elif q_type == 'choice':
                # 对选择题，提取垃圾分类类型
                if '属于' in question:
                    category = question.split('属于')[-1].strip('？')
                    return random.choice(self.choice_templates).format(category)
                return question
                
            return question
            
        except Exception as e:
            logger.error(f'生成问题变体出错: {str(e)}')
            return question
        
    def get_questions(self):
        """获取问答题目"""
        try:
            questions = []
            with open('quiz_questions.txt', 'r', encoding='utf-8') as f:
                lines = f.readlines()
                
            current_question = None
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                    
                if line.startswith('问题'):
                    if current_question:
                        questions.append(current_question)
                        
                    parts = line.split('：', 1)
                    if len(parts) < 2:
                        continue
                        
                    question_text = parts[1].strip()
                    # 判断题型并生成变体
                    if '判断' in question_text:
                        variant = self.generate_question_variant(question_text, 'true_false')
                        current_question = {
                            'type': 'true_false',
                            'original': question_text,
                            'question': variant,
                            'answer': None
                        }
                    else:
                        variant = self.generate_question_variant(question_text, 'choice')
                        current_question = {
                            'type': 'choice',
                            'original': question_text,
                            'question': variant,
                            'options': [],
                            'answer': None
                        }
                elif line.startswith('选项') and current_question and current_question['type'] == 'choice':
                    option = line.split('：', 1)[1].strip()
                    current_question['options'].append(option)
                elif line.startswith('答案'):
                    answer = line.split('：', 1)[1].strip()
                    if current_question:
                        current_question['answer'] = answer
            
            # 添加最后一个问题
            if current_question:
                questions.append(current_question)
                
            # 随机选择10道题目
            if len(questions) > 10:
                questions = random.sample(questions, 10)
            
            # 随机打乱选中的题目顺序
            random.shuffle(questions)
                
            return {
                'success': True,
                'questions': questions
            }
            
        except Exception as e:
            logger.error(f'获取题目出错: {str(e)}')
            return {
                'success': False,
                'error': f'获取题目出错: {str(e)}'
            }
    
    def check_answer(self, user_answer, correct_answer):
        """检查答案是否正确"""
        try:
            is_correct = user_answer.lower() == correct_answer.lower()
            
            return {
                'correct': is_correct,
                'message': '答对了！' if is_correct else '答错了，再试试吧！'
            }
        except Exception as e:
            logger.error(f'检查答案出错: {str(e)}')
            return {
                'error': f'检查答案出错: {str(e)}'
            }